package com.jt.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class MyMessageListener {

    private static final String EXCHANGE_NAME = "exchange-direct.order555";
    private static final String QUEUE_NAME = "queue_order555";
    private static final String ROUTING_KEY = "order555";


//    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = QUEUE_NAME, durable = "true"), exchange = @Exchange(value = EXCHANGE_NAME), key = {ROUTING_KEY}))
//    public void processMessage(String dataString, Message message, Channel channel) throws IOException {
//        System.out.println("消费端接收到了消息1》》》》 " + dataString);
//        System.out.println("消费端接收到了message》》》 " + message);
//        System.out.println("消费端接收到了channel》》》》 " + channel);
//        long deliveryTag = message.getMessageProperties().getDeliveryTag();
//        try {
//            /*deliveryTag为队列中每个消息的唯一标识，multiple为false 为单独一个消息，为true则为全部消息，批量*/
//            channel.basicAck(deliveryTag, false);
//        } catch (Exception e) {
//            /*requeue 控制消息是否重新放回队列*/
//            Boolean redelivered = message.getMessageProperties().getRedelivered();/*redelivered判断是否重复投递*/
//            if (redelivered) {
//                channel.basicNack(deliveryTag, false, false);
//            } else {
//                channel.basicNack(deliveryTag, false, true);
//            }
//            e.printStackTrace();
//        }
//    }

    //消息限流
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = QUEUE_NAME, durable = "true"), exchange = @Exchange(value = EXCHANGE_NAME), key = {ROUTING_KEY}))
    public void xianLiu(String dataString, Message message, Channel channel) throws IOException, InterruptedException {
        TimeUnit.SECONDS.sleep(1);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag, false);
    }
}
